import { createStore } from 'vuex'
import { login, getinfo } from "~/api/manager"
import { setToken, removeToken } from '~/composables/auth'
const store = createStore({
    state() {
        return {
            // 用户信息
            user: {},

            // 侧边宽度
            asideWidth:"250px",
            menus:[],
            ruleNames:[]
        }
    },
    mutations: {
        // 记录用户信息
        set_userinfo(state, user) {
            state.user = user
        },
        // 展开 / 收起侧边
        handleAsideWidth(state){
            state.asideWidth = state.asideWidth =="250px" ? "64px" : "250px"
        },
        set_menus(state,menus){
            state.menus = menus
        },
        set_rulenames(state,ruleNames){
            state.ruleNames = ruleNames
        }
    },
    actions: {
        // 登录
        login({ commit }, { username, password }) {
            return new Promise((resolov, reject) => {
                login(username, password).then(res => {
                    setToken(res.token)
                    resolov(res)
                }).catch(err => reject(err))
            })
        },
        // 获取当前登录用户信息
        getinfo({ commit }) {
            return new Promise((resolov, reject) => {
                getinfo().then(res => {
                    commit("set_userinfo", res)
                    commit("set_menus",res.menus)
                    commit("set_rulenames",res.ruleNames)
                    resolov(res)
                }).catch(err => reject(err))
            })
        },
        // 退出登录
        logout({commit}) {
            // 移除cookie里的token
            removeToken()
            // 清除当前用户状态 vuex
            commit("set_userinfo",{})
        }
    }
})

export default store